<template>
  <div class="login-container">
    <el-card class="login-card">
      <!-- 头部返回按钮 -->
      <div class="header">
        <el-button 
          class="back-btn" 
          type="text" 
          @click="router.push('/login')"
          :icon="ArrowLeft"
        >
          返回登录
        </el-button>
        <h1 class="title">用户注册</h1>
      </div>

      <div class="form-wrapper">
        <!-- 用户名 -->
        <div class="form-item">
          <label class="form-label">用户名</label>
          <el-input
            v-model="form.username"
            placeholder="请输入用户名（唯一标识）"
            size="large"
            :prefix-icon="User"
          />
        </div>

        <!-- 密码 -->
        <div class="form-item">
          <label class="form-label">密码</label>
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码（至少3位）"
            size="large"
            :prefix-icon="Lock"
            show-password
          />
        </div>

        <!-- 确认密码 -->
        <div class="form-item">
          <label class="form-label">确认密码</label>
          <el-input
            v-model="form.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            size="large"
            :prefix-icon="Lock"
            show-password
          />
        </div>

        <!-- 姓名 -->
        <div class="form-item">
          <label class="form-label">真实姓名</label>
          <el-input
            v-model="form.name"
            placeholder="请输入真实姓名"
            size="large"
            :prefix-icon="Avatar"
          />
        </div>

        <!-- 联系方式 -->
        <div class="form-item">
          <label class="form-label">联系方式</label>
          <el-input
            v-model="form.contact"
            placeholder="请输入手机/邮箱"
            size="large"
            :prefix-icon="Message"
          />
        </div>
      </div>

      <div class="action-buttons">
        <el-button 
          type="primary" 
          size="large" 
          class="register-btn"
          @click="handleRegister"
          :loading="isLoading"
        >
          立即注册
        </el-button>

        <!-- 底部登录链接 -->
        <div class="footer-link">
          <span>已有账号？</span>
          <el-link 
            type="primary" 
            @click="router.push('/login')"
            :underline="false"
          >
            立即登录
          </el-link>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { User, Lock, Message, Avatar, ArrowLeft } from '@element-plus/icons-vue'
import { ref, h } from 'vue'
import axios from 'axios'
import { ElNotification } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()

const form = ref({
  username: '',
  password: '',
  confirmPassword: '',
  name: '',
  contact: ''
})

const isLoading = ref(false)

// 表单验证
const validateForm = () => {
  if (!form.value.username || 
      !form.value.password || 
      !form.value.name || 
      !form.value.contact) {
    ElNotification({
      title: '错误',
      message: '请填写所有必填项',
      type: 'error',
    })
    return false
  }

  if (form.value.password.length < 3) {
    ElNotification({
      title: '错误',
      message: '密码长度不能少于3位',
      type: 'error',
    })
    return false
  }

  if (form.value.password !== form.value.confirmPassword) {
    ElNotification({
      title: '错误',
      message: '两次输入的密码不一致',
      type: 'error',
    })
    return false
  }

  return true
}

// 注册处理
const handleRegister = async () => {
  if (!validateForm()) return

  isLoading.value = true

  try {
    const response = await axios.post('http://localhost:3000/users/register', {
      username: form.value.username,
      password: form.value.password,
      name: form.value.name,
      contact: form.value.contact
    })

    // 修改判断逻辑：直接验证返回的user_id是否为有效数字
    if (typeof response.data === 'number' && response.data > 0) {
      ElNotification({
        title: '注册成功',
        message: `用户ID：${response.data}，请使用账号登录系统`,
        type: 'success',
        duration: 4000,
        btn: h(
          'el-button',
          {
            type: 'primary',
            size: 'small',
            onClick: () => router.push('/login')
          },
          '前往登录'
        ),
      })
      
      // 清空表单
      form.value = {
        username: '',
        password: '',
        confirmPassword: '',
        name: '',
        contact: ''
      }
    } else {
      throw new Error('收到无效的服务器响应')
    }
  } catch (error) {
    let message = '注册失败，请稍后再试'
    
    // 根据不同的错误类型细化提示
    if (error.response) {
      // 处理HTTP错误状态码
      switch (error.response.status) {
        case 400:
          message = '请求参数错误'
          break
        case 409:
          message = '用户名已被占用'
          break
        case 500:
          message = '服务器内部错误'
          break
      }
    } else if (error.message.includes('无效的服务器响应')) {
      message = '服务器返回格式异常'
    }

    ElNotification({
      title: '注册失败',
      message: message + (error.response?.data ? `（${error.response.data}）` : ''),
      type: 'error',
      duration: 5000
    })
    
    console.error('注册错误详情:', {
      error: error.message,
      response: error.response?.data,
      config: error.config
    })
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  width: 100vw; /* 添加视口宽度 */
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
  box-sizing: border-box; /* 防止内边距影响尺寸 */
}

/* 修改卡片样式 */
.login-card {
  width: 100%; /* 改为百分比宽度 */
  max-width: 600px; /* 设置最大宽度 */
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  position: relative;
  margin: 0 auto; /* 确保居中 */
}

.header {
  text-align: center;
  margin-bottom: 30px;
  position: relative;
}

.title {
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
  margin-top: 10px;
}

.back-btn {
  position: absolute;
  left: 0;
  top: 0;
  color: #666;
  padding: 0;
}

.back-btn:hover {
  color: var(--el-color-primary);
}

.form-wrapper {
  margin: 30px 0;
}

.form-item {
  margin-bottom: 25px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  color: #666;
  font-size: 14px;
}

:deep(.el-input) {
  --el-input-height: 48px;
  --el-input-border-radius: 8px;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px var(--el-color-primary) inset;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 30px;
}

.register-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  letter-spacing: 1px;
}

.footer-link {
  text-align: center;
  color: #666;
  margin-top: 15px;
}

.footer-link span {
  margin-right: 8px;
}

@media (max-width: 768px) {
  .login-card {
    padding: 30px 20px; /* 减小内边距 */
    width: 95%; /* 在小屏幕上增加宽度占比 */
  }
  
  .title {
    font-size: 20px;
  }
  
  /* 移动端按钮垂直排列 */
  .action-buttons {
    flex-direction: column;
  }
}

:deep(.el-input__prefix-inner) {
  margin-right: 8px;
}
</style>